package com.bitcat.todoapp.demo.newslistdemo

import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.bitcat.todoapp.R
import com.bitcat.todoapp.databinding.ActivityRecyclerViewDemoBinding
import com.bitcat.todoapp.demo.netdemo.NewsBean
import com.bitcat.todoapp.demo.netdemo.RetrofitClient
import retrofit2.Call
import retrofit2.Response

class RecyclerViewDemoActivity : AppCompatActivity() {

    private lateinit var binding: ActivityRecyclerViewDemoBinding

    private lateinit var newsAdapter: NewsAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityRecyclerViewDemoBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        newsAdapter = NewsAdapter(mutableListOf())

        //线性布局
//        binding.recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

        //网格布局
//        binding.recyclerView.layoutManager = GridLayoutManager(this,2)

        //瀑布流
        binding.recyclerView.layoutManager = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
        binding.recyclerView.adapter = newsAdapter

        fetchNews()
    }

    private fun fetchNews() {
        RetrofitClient.newsApi.getNews().enqueue(object : retrofit2.Callback<NewsBean> {
            override fun onResponse(call: Call<NewsBean>, response: Response<NewsBean>) {

                //请求失败
                if (!response.isSuccessful){
                    Log.e("TAG", "onResponse: ${response.code()}")
                    return
                }

                //请求成功
                val newsBean = response.body()
                newsBean?.let {
                    newsAdapter.updateNews(newsBean.news)
                }

            }

            override fun onFailure(call: Call<NewsBean>, t: Throwable) {
                Log.e("TAG", "onResponse: ${t.message}")
            }
        })
    }
}